#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

int count= 0;

//创建了一个读写锁
pthread_rwlock_t rwlock;

void *read_test(void *arg){
    //读锁的存在提高了并发性，使得多个线程可以同时读取共享数据
    pthread_rwlock_rdlock(&rwlock);
    printf("read %d\n", count);
    pthread_rwlock_unlock(&rwlock);
}

void *write_test(void *arg){
    pthread_rwlock_wrlock(&rwlock);
    count++;
    printf("write %d\n", count);
    pthread_rwlock_unlock(&rwlock);
}

int main(int argc, char const *argv[])
{   
    pthread_t write[2];
    pthread_t read[6];
    //读写锁默认是读优先的，即读锁优先级高于写锁，下面的代码中设置了写优先
    pthread_rwlockattr_t attr;
    pthread_rwlockattr_init(&attr);
    pthread_rwlockattr_setkind_np(&attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);

    pthread_rwlock_init(&rwlock, &attr);
    for (int i = 0; i < 2; i++)
    {
        pthread_create(&write[i], NULL, write_test, (void *)&i);
    }
    sleep(1);

    for (int i = 0; i < 6; i++)
    {
        pthread_create(&read[i], NULL, read_test, (void *)&i);
    }

    for (int i = 0; i < 2; i++)
    {
        pthread_join(write[i], NULL);
    }
    
    for (int i = 0; i < 6; i++){
        pthread_join(read[i], NULL);
    }
    
    pthread_rwlock_destroy(&rwlock);
    
    
    
    /* code */
    return 0;
}
